package com.faneui.transfer.gateway.utils;

import com.faneui.transfer.gateway.exception.WmsException;
import com.faneui.transfer.gateway.exception.WmsExceptionEnum;
import com.faneui.transfer.gateway.model.*;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

public class BeanAssemblyUtils<T> {

	private static BeanUtilsBean
            beanUtilsBean = new BeanUtilsBean(new ConvertUtilsBean() {
		@SuppressWarnings({ "unchecked", "rawtypes" })
		@Override
		public Object convert(String value, Class clazz) {
			if (clazz.isEnum()) {
				return Enum.valueOf(clazz, value);
			} else {
				return super.convert(value, clazz);
			}
		}
	});

	public static <T> T mapToBean(Class<T> clazz, Map<String, ? extends Object> map)
			throws InstantiationException, IllegalAccessException, InvocationTargetException {
		T result = clazz.newInstance();
		beanUtilsBean.populate(result, map);
		return result;
	}

	public static OutputBean OK() {
		return new OutputBean(WmsExceptionEnum.SUCCEED.getCode(),"成功");
	}

	public static <T> OutputObjectBean<T> OK(T t) {

		OutputObjectBean<T> output = new OutputObjectBean<T>(WmsExceptionEnum.SUCCEED.getCode(),
                "成功", t);
		return output;
	}

	public static <T> OutputPagerBean<T> OK(Pager<T> pager) {

		OutputPagerBean<T> output = new OutputPagerBean<T>(WmsExceptionEnum.SUCCEED.getCode(),
                "成功", pager);
		return output;
	}

	public static <T> OutputArrayBean<T> OK(List<T> array) {

		OutputArrayBean<T> output = new OutputArrayBean<T>(WmsExceptionEnum.SUCCEED.getCode(),
                "成功", array);
		return output;
	}

	public static <T> OutputBean ERROR(WmsException e) {
		OutputBean output = new OutputBean(e.getCode(), e.getMessage());
		return output;
	}
}
